﻿using System;
using System.Configuration;
using ControleRepresentante.Common;

namespace ControleRepresentanteSync.Logic
{
    public class ConfigurationInfo
    {
        private const string UsernameKey = "Username";
        private const string PasswordKey = "Password";

        private string m_Username;
        private string m_Password;

        public ConfigurationInfo()
        {
            SetUser();
        }

        public bool IsValid
        {
            get
            {
                return !StringHelper.IsNullOrWhiteSpace(Username) &&
                       !StringHelper.IsNullOrWhiteSpace(Password);
            }
        }

        private void SetUser()
        {
            m_Username = ConfigurationManager.AppSettings[UsernameKey];
            m_Password = ConfigurationManager.AppSettings[PasswordKey];
        }

        public string Username
        {
            get { return m_Username; }
            private set
            {
                m_Username = value;
                SetValue(UsernameKey, value);
            }
        }

        public string Password
        {
            get { return m_Password; }
            private set
            {
                m_Password = value;
                SetValue(PasswordKey, value);
            }
        }

        public event EventHandler UserSettingsChanged;

        public void SetUserSettings(string username, string password)
        {
            Username = username;
            Password = password;
            if (UserSettingsChanged != null)
                UserSettingsChanged(this, EventArgs.Empty);
        }

        private static void SetValue(string key, string value)
        {
            Configuration configuration =
                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            configuration.AppSettings.Settings.Remove(key);
            configuration.AppSettings.Settings.Add(key, value);
            configuration.Save(ConfigurationSaveMode.Modified);
        }
    }
}
